package cn.edu.sdu.sol.intake_system.security;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        // 获取用户的角色列表
        for (GrantedAuthority authority : authentication.getAuthorities()) {
            String role = authority.getAuthority();
            if ("ADMIN".equals(role)) {
                // 如果角色是ADMIN，执行相应的操作
                UserDetails userDetails = (UserDetails) authentication.getPrincipal();
                // 检查用户的角色是否为"ADMIN"
                if (userDetails.getAuthorities().contains(new SimpleGrantedAuthority("ADMIN"))) {
                    // 在这里添加您的自定义逻辑
                    // 例如，将用户信息放入 SecurityContextHolder
                    setUserDetailsInSecurityContext(userDetails);
                    // 进行其他操作
                }
            }
        }
    }

    private void setUserDetailsInSecurityContext(UserDetails userDetails) {
        Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }
}